import telnetlib,time
import matplotlib.pyplot as plt

tn=telnetlib.Telnet()
tn.open("192.168.13.35",4444)

def get_info():
    # 尝试通信
    tn.write('test'.encode('ascii')+b'\n')
    time.sleep(0.1)
    print(tn.read_very_eager().decode('ascii'))

    tn.write('metrics:cpu'.encode('ascii')+b'\n')
    time.sleep(2)
    # print('cpu:',tn.read_very_eager().decode('ascii'))
    cpu=tn.read_very_eager().decode('ascii')
    tn.write('metrics:memory'.encode('ascii')+b'\n')
    time.sleep(2)
    # print('mem:',tn.read_very_eager().decode('ascii'))
    mem=tn.read_very_eager().decode('ascii')
    tn.write('metrics:network'.encode('ascii')+b'\n')
    time.sleep(2)
    # print('network',tn.read_very_eager().decode('ascii'))
    network=tn.read_very_eager().decode('ascii')
    tn.write('metrics:disks'.encode('ascii')+b'\n')
    time.sleep(2)
    # print('disks',tn.read_very_eager().decode('ascii'))
    disks=tn.read_very_eager().decode('ascii')
    # tn.write(b'exit\n')
    return cpu,mem,network,disks

def ax_table(times,index,name,id,color):
    plt.subplot(id)
    plt.plot(times,index,label=name,color=color)
    plt.ylabel(name+'使用率%',fontsize=14)
    plt.xticks(rotation=30,fontsize=8)
    plt.yticks(range(0,110,10))


def UI():
    plt.rcParams["font.sans-serif"] = ['SimHei']  #使正常显示中文
    plt.ion()
    plt.figure(figsize=(10,10))  # 生成一个10-10的画布
    cpu=[]
    mem = []
    network = []
    disks = []
    times = []
    while True:
        t = time.strftime("%H:%M:%S",time.localtime())
        cpu_info,mem_info,network_info,disks_info = get_info()
        times.append(t)
        # print(disks_info)
        cpu.append(int(eval(cpu_info.strip().split("\t\n")[0])))
        mem.append(int(eval(mem_info.strip().split("\t\n")[0])))
        network.append(int(eval(network_info.strip().split("\t\n")[0])))
        disks.append(int(eval(disks_info.strip().split("\t\n")[0])))
        ax_table(times,cpu,'CPU',221,'b')
        ax_table(times,mem,"内存",222,'g')
        ax_table(times,network,"网络",223,'y')
        ax_table(times,disks,"磁盘",224,'r')
        plt.pause(1)
    plt.ioff()
    plt.show()

if __name__ == '__main__':
    # print(get_info())
    UI()


